<template>
    <div class="salary-chart" ref="chartContainer"></div>
  </template>
  
  <script>
  import * as echarts from 'echarts';
  
  export default {
    name: 'SalaryChart',
    props: {
      chartData: {
        type: Array,
        required: true,
        validator: data => data.every(item => 
          'salaryRange' in item && 
          'count' in item
        )
      }
    },
    data() {
      return {
        chart: null
      };
    },
    mounted() {
      this.initChart();
      window.addEventListener('resize', this.handleResize);
    },
    beforeDestroy() {
      window.removeEventListener('resize', this.handleResize);
      if (this.chart) {
        this.chart.dispose();
      }
    },
    methods: {
      initChart() {
        this.chart = echarts.init(this.$refs.chartContainer,null,{
            width: 800,
            height: 340
        });
        this.updateChart();
      },
      handleResize() {
        if (this.chart) {
          this.chart.resize();
        }
      },
      updateChart() {
        const option = {
          title: {
            text: '毕业生薪资水平',
            left: 'center',
            textStyle: {
              color: '#2c3e50',
              fontSize: 18
            }
          },
          tooltip: {
            trigger: 'axis',
            backgroundColor: 'rgba(50,50,50,0.95)',
            borderWidth: 0,
            textStyle: {
              color: '#fff'
            },
            formatter: params => {
              const data = params[0];
              return `薪资区间: ${data.name}<br>人数: ${data.value}`;
            }
          },
          xAxis: {
            type: 'category',
            data: this.chartData.map(item => item.salaryRange),
            axisLabel: {
              rotate: 45
            }
          },
          yAxis: {
            type: 'value',
            name: '人数'
          },
          series: [{
            name: '薪资分布',
            type: 'bar',
            barWidth: '60%',
            data: this.chartData.map(item => ({
              value: item.count,
              name: item.salaryRange,
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#36DBCA' }, // 蓝绿色渐变
                  { offset: 1, color: '#2B8AFF' }
                ])
              }
            })),
            animationDelay: idx => idx * 100
          }]
        };
        this.chart.setOption(option);
      }
    },
    watch: {
      chartData: {
        handler() {
          if (this.chart) {
            this.updateChart();
          }
        },
        deep: true
      }
    }
  };
  </script>
  
  <style scoped>
  .salary-chart {
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0,0,0,0.1);
    padding: 20px;
  }
  </style>